package com.chuzhiyun.chengguoxy.feature.internship.project;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.help.InputtipsQuery;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chuzhiyun.chengguoxy.R;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.provider.SyncStateContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Tip;
import com.chuzhiyun.chengguoxy.utlis.CustomClickListener;
import com.chuzhiyun.chengguoxy.utlis.LocationUtils;
import com.chuzhiyun.chengguoxy.utlis.NewItemClickListener;
import com.chuzhiyun.chengguoxy.utlis.StatusBarUtil;
import com.chuzhiyun.chengguoxy.utlis.StringUtils;
import com.chuzhiyun.chengguoxy.utlis.ToastCustom;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@SuppressWarnings("FieldMayBeFinal")
public class MapLocationActivity extends AppCompatActivity {

    MapView mMapView = null;
    private AMap aMap;
    LatLng latLng;
    private String adCode = "";
    private String street = "";

    private String cityName = "";
    private String searchStr = "";
    private TextView cityText;
    private RecyclerView recyclerView;
    private MapLocationActivity.MyAdapter myAdapter;
    private List<Tip>dataSource = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map_location);
        ImageView backImg = findViewById(R.id.iv_back);
        backImg.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                onBackPressed();
            }
        });
        TextView titleText =findViewById(R.id.tv_title);
        titleText.setText("选择打卡地址");

        ImageView localImg = findViewById(R.id.local_Img);
        localImg.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                recyclerView.setVisibility(View.GONE);
                setupLocal();
            }
        });

        TextView rightText = findViewById(R.id.right_tv);
        rightText.setVisibility(View.VISIBLE);
        rightText.setText("保存");
        rightText.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                Intent intent = new Intent();
                if (!StringUtils.isBlank(street)){
                    intent.putExtra("adCode",adCode);
                    intent.putExtra("street",street);
                    String latitudeStr = latLng.latitude+"";
                    String longitudeStr = latLng.longitude+"";
                    intent.putExtra("latitude",latitudeStr);
                    intent.putExtra("longitude",longitudeStr);
                }
                setResult(123, intent);
                onBackPressed();
            }
        });

        cityText = findViewById(R.id.city_Text);

        RelativeLayout chooseRl = findViewById(R.id.choose_City);
        chooseRl.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {

            }
        });

        EditText searchText = findViewById(R.id.search_Edit);
        searchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                searchStr = searchText.getText().toString();
                if (StringUtils.isEmpty(searchStr)){
                    recyclerView.setVisibility(View.GONE);
                }
                else {
                    if (searchStr.length()==0) {
                        recyclerView.setVisibility(View.GONE);
                    }
                    else {
                        searchPoiList();
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        ImageView searchImg = findViewById(R.id.search_Img);
        searchImg.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                searchPoiList();
            }
        });

        recyclerView = findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new GridLayoutManager(this, 1));
        myAdapter = new MyAdapter(R.layout.item_local_address, dataSource);
        recyclerView.setAdapter(myAdapter);
        myAdapter.notifyDataSetChanged();
        myAdapter.setOnItemClickListener(new NewItemClickListener() {
            @Override
            protected void onSingleClick(BaseQuickAdapter adapter, View view, int position) {
                Tip tip = dataSource.get(position);
                recyclerView.setVisibility(View.GONE);
                latLng =new LatLng(tip.getPoint().getLatitude(),tip.getPoint().getLongitude());
                adCode = tip.getAdcode();
                street = tip.getName();
                //aMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
                addMarkerInScreenCenter(latLng);
            }
        });

        //获取地图控件引用
        mMapView = (MapView) findViewById(R.id.map);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        mMapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        Objects.requireNonNull(this.getSupportActionBar()).hide();
        setStatusBar();
        setupLocal();

    }

    /*开始定位*/
    private void setupLocal() {
        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE) ;//定位一次，且将视角移动到地图中心点。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        aMap.getUiSettings().setMyLocationButtonEnabled(false);
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false
        try {
            LocationUtils.getInstance().getLocation(this, new LocationUtils.OnLocationChangedListener() {
                @Override
                public void onSuccess(AMapLocation amapLocation) {
                    double latitude = amapLocation.getLatitude();
                    double longitude = amapLocation.getLongitude();
                    latLng = new LatLng(latitude,longitude);
                    adCode = amapLocation.getAdCode();
                    street = amapLocation.getPoiName();
                    aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,16));
                    cityName = amapLocation.getCity();
                    cityText.setText(cityName);
                }

                @Override
                public void onFail(int errCode, String errInfo) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void searchPoiList(){

        //第二个参数传入null或者“”代表在全国进行检索，否则按照传入的city进行检索
        InputtipsQuery inputQuery = new InputtipsQuery(searchStr, cityName);
        inputQuery.setCityLimit(true);//限制在当前城市
        Inputtips inputTips = new Inputtips(this, inputQuery);
        inputTips.setInputtipsListener(new Inputtips.InputtipsListener() {
            @Override
            public void onGetInputtips(List<Tip> list, int i) {
                System.out.println(list);
                dataSource.clear();
                if (list.size()!=0){
                    recyclerView.setVisibility(View.VISIBLE);
                    dataSource.addAll(list);
                    myAdapter.notifyDataSetChanged();
                }
            }
        });
        inputTips.requestInputtipsAsyn();
    }

    private void addMarkerInScreenCenter(LatLng locationLatLng) {
        LatLng latLng = aMap.getCameraPosition().target;
        MarkerOptions markerOptions = new MarkerOptions()
                .position(locationLatLng)
                .draggable(true)
                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.local_mark));
        aMap.addMarker(markerOptions);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mMapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mMapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(@NotNull Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }

    private void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (isUseFullScreenMode()) {
                StatusBarUtil.setStatusBarColor(this, R.color.white);
            } else {
                StatusBarUtil.setStatusBarColor(this, getStatusBarColor());
            }

            if (isUseBlackFontWithStatusBar()) {
                StatusBarUtil.setLightStatusBar(this, true, isUseFullScreenMode());
            }

        }
    }

    /**
     * 是否设置成透明状态栏，即就是全屏模式
     */
    protected boolean isUseFullScreenMode() {
        return false;
    }

    /**
     * 更改状态栏颜色，只有非全屏模式下有效
     */
    protected int getStatusBarColor() {
        return R.color.white;
    }

    /**
     * 是否改变状态栏文字颜色为黑色，默认为黑色
     */
    protected boolean isUseBlackFontWithStatusBar() {
        return true;
    }

    public static class MyAdapter extends BaseQuickAdapter<Tip, BaseViewHolder> {
        public MyAdapter(int layoutResId, List<Tip> data) {
            super(layoutResId, data);
        }
        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        protected void convert(@NotNull BaseViewHolder helper, Tip item) {
            helper.setText(R.id.address_Text,item.getName());
        }
    }
}
